package com.zjl.tools.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SqlUtil {
    public static void main(String[] args) {

    }
    public static Connection getConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test?generateSimpleParameterMetadata=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
        String username = "root";
        String password = "root";
        return DriverManager.getConnection(url, username, password);
    }

    public static void runSql(Connection connection, String path) throws Exception {
        runSql(connection, new File(path));
    }

    public static void runSql(Connection connection, File file) throws Exception {
        runSql(connection, Arrays.asList(file));
    }

    public static void runSql(Connection connection, List<File> files) throws Exception {
        try (Statement statement = connection.createStatement();
        ) {
            for (File file : files) {
                try (BufferedReader br = new BufferedReader(new FileReader(file));) {
                    StringBuilder sb = new StringBuilder();
                    int k = 0;
                    String data;
                    while ((data = br.readLine()) != null) {
                        sb.append(data);
                        if (data.endsWith(";") && !data.endsWith("\\\\;")) {
                            statement.addBatch(sb.toString());
                            k++;
                            sb.setLength(0);//清空
                        } else {
                            sb.append(System.lineSeparator());//换行补回去
                        }
                    }
                    statement.executeBatch();//执行sql
                    sb.setLength(0);//清空
                }
            }
        }
    }
}
